<template>
  <div class="course-management" style="display:flex;flex-direction:column;justify-content: center;">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div style="width: 420px;border-bottom: 2px solid rgb(36, 67, 130);margin-bottom: 15px;">
        <p class="cousename">{{ courseName }}</p>
      </div>
      <div style="display: flex; gap: 10px;">
        <el-button 
          type="primary" 
          class="create-button" 
          @click="handleCreateChapter"
        >
          新建章节
        </el-button>
        <!-- <el-upload
          class="upload-btn"
          action="#"
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
        > -->
          <el-button class="create-button" type="primary" @click="openResourceDialog">添加资源</el-button>
        <!-- </el-upload> -->
      </div>
    </div>

    <!-- 主体布局 -->
    <div class="main-layout" style="display:flex;flex-direction:row">
      <!-- 左侧章节树 -->
      <div class="left-tree">
        <el-tree
          :data="chapters"
          node-key="id"
          default-expand-all
          @node-dblclick="handleNodeDblclick"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          style="font-size: 16px;"
        >
          <template #default="{ node, data }" >
            <span class="custom-tree-node">
              <el-icon v-if="data.type === 'chapter'"><FolderOpened /></el-icon>
              <el-icon v-else><Files /></el-icon>
               <span>{{ short(node.label) }}</span>
              
              <!-- 节点操作按钮 -->
              <span class="node-actions" >
                <el-button 
                  v-if="data.type === 'chapter'"
                  link
                  type="primary"
                  size="regular"
                  @click.stop="handleCreateSection(data)"
                >
                  <el-icon><CirclePlus /></el-icon>
                </el-button>
                <el-button
                  v-if="data.type === 'chapter'"
                  link
                  type="danger"
                  size="regular"
                  @click.stop="handleDeleteNode(data)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
                <el-button
                  v-if="data.type === 'chapter'"
                  link
                  size="regular"
                  @click.stop="handleRenameNode(data)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </span>
            </span>
          </template>
        </el-tree>
      </div>

      <!-- 右侧资源管理 -->
      <div class="right-content">
        <div v-if="selectedSection" style="margin-top: -20px;">
          <div class="section-header">
            <h3 class="section-title">
              {{ selectedSection.label }}
            </h3>
            <div> 
              <el-button 
                link
                type="primary"
                @click="handleRenameNode(selectedSection)"
              >
                <el-icon><Edit /></el-icon>重命名
              </el-button>
              <el-button 
                link
                type="danger"
                @click="handleDeleteNode(selectedSection)"
              >
                <el-icon><Delete /></el-icon>删除小节
              </el-button>
            </div>
          </div>

          <!-- 资源类型导航 -->
          <div class="resource-types">
            <el-button 
              v-for="type in resourceTypes" 
              :key="type.value"
              :type="activeType === type.value ? 'primary' : ''"
               @click="activeType = type.value"
            >
              <el-icon :size="16">
                <component :is="type.icon" />
              </el-icon>
              {{ type.label }}
            </el-button>
          </div>

          <!-- 资源列表 -->
          <div class="resource-list">
            <template v-if="filteredResources.length">
              <div 
                v-for="resource in filteredResources" 
                :key="resource.id" 
                class="resource-item"
              >
                <!-- 显示视频 -->
                <div v-if="resource.type === 'video'" class="video-cover">
                  <div class="video-cover-container" @click="handleAddResource(resource)">
                    <img :src="resource.cover" style="margin-right:20px" alt="视频封面" width="120" height="80"/>
                    <div class="play-button">
                      <img src="@/assets/picture/play.png" alt="播放" />
                    </div>
                  </div>
                  <div class="document-info">
                    <span class="resource-name">{{ resource.name }}</span>
                    <span class="upload-time">上传时间：{{ resource.uploadTime }}</span>
                  </div>
                </div>
                <!-- 显示图片 -->
                <div v-if="resource.type === 'image'" style="display:flex;align-items: center;margin-left:20px;object-fit: cover;">
                  <img :src="resource.cover" alt="图片" style="margin-right:20px;object-fit: cover" width="80" height="120"/>
                  <div class="document-info">
                    <span class="resource-name">{{ resource.name }}</span>
                    <span class="upload-time">上传时间：{{ resource.uploadTime }}</span>
                  </div>
                </div>
                <!-- 显示文档 -->
                <div v-if="resource.type === 'document'" class="document-item" style="display:flex;align-items: center;margin-left:20px;">
                  <div class="document-icon">
                    <el-icon><Document /></el-icon>
                  </div>
                  <div class="document-info">
                    <span class="resource-name">{{ resource.name }}</span>
                    <span class="upload-time">上传时间：{{ resource.uploadTime }}</span>
                  </div>
                </div>
                <!-- 显示PPT -->
                <div v-if="resource.type === 'ppt'" class="ppt-item" style="display:flex;align-items: center;margin-left:20px;">
                  <div class="ppt-icon">
                    <el-icon><Files /></el-icon>
                  </div>
                  <div class="document-info">
                    <span class="resource-name">{{ resource.name }}</span>
                    <span class="upload-time">上传时间：{{ resource.uploadTime }}</span>
                  </div>
                </div>
                <div class="resource-actions">
                  <el-button size="mini" @click="handlePreview(resource)">查看</el-button>
                  <el-button size="mini" type="danger" @click="handleDelete(resource)" style="margin-right:20px; ">删除</el-button>
                </div>
              </div>
            </template>
            <div v-else class="empty-resource">
              <el-empty description="当前章节暂无资源" />
            </div>
          </div>
        </div>

        <div v-else class="empty-tip">
          请先选择或创建章节小节
        </div>
      </div>
    </div>

    <!-- 创建对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="formData">
        <el-form-item label="名称">
          <el-input v-model="formData.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmCreate">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="renameDialogVisible" title="重命名">
      <el-form :model="renameFormData">
        <el-form-item label="新名称">
          <el-input v-model="renameFormData.newName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="renameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmRename">确定</el-button>
      </template>
    </el-dialog>

 <!-- 资源选择模态框 -->
    <div v-if="visibleResourceDialog" class="modal-overlay" @click.self="closeResourceDialog">
      <div class="modal-content">
        <component 
          :is="currentResourcePage"
          :is-select-mode="true"
          @video-selected="handleVideoSelected"
          @document-selected="handleDocumentSelected"
          @image-selected="handleImageSelected"
        />
        <div class="modal-actions" style="width:80vw">
          <div class="selected-info">
            <p v-if="selectedResource" style="margin:0px;padding:0px;background:white">已选资源: {{ selectedResource.name }} (ID: {{ selectedResource.id }}) </p>
          </div>
          <div>
            <el-button @click="closeResourceDialog">取消</el-button>
            <el-button type="primary" @click="handleConfirmResource">确认添加</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, computed,onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router'
import {
  FolderOpened,
  Files,
  Document,
  VideoPlay,
  Picture,
  Delete,
  Edit,
  CirclePlus,
} from '@element-plus/icons-vue'
import T_VideosPage from './T_VideosPage.vue';
import T_WordPage from './T_WordPage.vue';
import T_ExamBankPage from './T_ImagesPage.vue';
import {
  fetchChapters,
  fetchChapterResources,
  fetchClassDetails,
  deleteUnits,
  createChapter,
  createSection,
  renameUnit,
  deleteResources,
  addResourceToSection
} from '@/services/api';
const components = {
  T_VideosPage,
  T_WordPage,
  T_ExamBankPage
};
const short = (txt, n = 15) =>  // 从18改为15
  txt.length > n ? txt.slice(0, n) + '…' : txt;
const router = useRouter() // 在此处初始化
const visibleResourceDialog = ref(false);
const currentResourcePage = ref(null);
const renameDialogVisible = ref(false)
const renameFormData = ref({
  node: null,
  newName: ''
})

// 修改删除节点方法
const handleDeleteNode = async (node) => {
  try {
    await ElMessageBox.confirm(
      `确定删除 ${node.label} 吗？`,
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const res = await deleteUnits(node.id);
    if(res.data.status === 1) {
      ElMessage.success('删除成功');
      const sem_id = localStorage.getItem('selectedClassId');
      const response = await fetchChapters(sem_id);
      chapters.value = transformChapterData(response.data.data);
      if(selectedSection.value?.id === node.id) {
        selectedSection.value = null;
      }
    }
  } catch (error) {
    // 用户取消操作自动捕获
  }
}

const handlePreview = (resource) => {
  router.push({
    path: 'ResourceViewer',
    query: {
      type: resource.type,
      url: resource.url,
      name: resource.name,
      uploadTime: resource.uploadTime
    }
  });
};
const handleConfirmCreate = async () => {
  try {
    const sem_id = localStorage.getItem('selectedClassId');
    if(currentAction.value === 'chapter') {
      // 创建章节
      const res = await createChapter({
        unit_title: formData.value.name,
        unit_module: null,
        semester_id: sem_id
      });
      if(res.data.status === 1) {
        // 重新加载章节数据
        ElMessage.success('创建成功');
        const response = await fetchChapters(sem_id);
        chapters.value = transformChapterData(response.data.data);
      }
    } else {
      // 创建小节
      const res = await createSection({
        unit_title: formData.value.name,
        unit_module: formData.value.parentId,
        semester_id: sem_id
      });
      if(res.data.status === 1) {
        // 重新加载章节数据
        const response = await fetchChapters(sem_id);
        chapters.value = transformChapterData(response.data.data);
      }
    }
    dialogVisible.value = false;
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  }
}
 const courseName = ref(''); // 添加课程名称引用
const loadCourseName = async () => {
  try {
    const response = await fetchClassDetails(localStorage.getItem('selectedClassId'), localStorage.getItem('id'));
    if (response.data.status === 1) {
      courseName.value = response.data.data.semester_name;
    }
  } catch (error) {
    console.error('加载课程详情失败:', error);
  }
};
// 章节数据
const chapters = ref([])
// 选中的资源列表

// 初始化加载章节
onMounted(async () => {
  loadCourseName();
  try {
    // 使用路由参数中的 sem_id ↓
    const sem_id = localStorage.getItem('selectedClassId')
    console.log(sem_id)
    const response = await fetchChapters(sem_id)
    chapters.value = transformChapterData(response.data.data)
  } catch (error) {
    console.error('加载章节失败:', error)
  }
})
// 转换章节数据结构
const transformChapterData = (apiData) => {
  return apiData.map(chapter => ({
    id: chapter.unit_id,
    label: chapter.unit_title,
    type: 'chapter',
    children: chapter.children?.map(section => ({
      id: section.unit_id,
      label: section.unit_title,
      type: 'section'
    })) || []
  }))
}

// 点击章节节点时加载资源
const handleNodeClick = async (data) => {
   if(data.type === 'section') {
    try {
      const response = await fetchChapterResources(data.id)
      // 将资源数据绑定到当前小节 ↓
      data.resources = transformResourceData(response.data.data)
      selectedSection.value = data
    } catch (error) {
      console.error('加载资源失败:', error)
    }
  }
}

// 转换资源数据结构
const transformResourceData = (apiData) => {
  return apiData.map(item => ({
    id: item.unit_re_id,
    name: item.resource.resource_name,
    type: item.resource.resource_type === 'word' ? 'document' : 
          item.resource.resource_type === 'pic' ? 'image' : 
          item.resource.resource_type.toLowerCase(),  // 转换word->document, pic->image
    uploadTime: item.create_time,
    cover: item.video_cover,  // 保持原有逻辑
    url: item.resource.resource_url
  }))
}

// 资源类型配置
const resourceTypes = ref([
  { value: 'document', label: '文档', icon: Document },
  { value: 'ppt', label: 'PPT', icon: Files },
  { value: 'video', label: '视频', icon: VideoPlay },
  { value: 'image', label: '图片', icon: Picture }
])



const closeResourceDialog = () => {
  visibleResourceDialog.value = false;
  selectedResource.value = null;
};

// 响应式数据
const activeType = ref('document')
const selectedSection = ref(null)
const dialogVisible = ref(false)
const formData = ref({ type: '', parentId: null })
const currentAction = ref('') // 'chapter' | 'section'
const selectedResource = ref(null);



const filteredResources = computed(() => {
  return selectedSection.value?.resources?.filter(r => r.type === activeType.value) || []
})

const dialogTitle = computed(() => 
  currentAction.value === 'chapter' ? '新建章节' : '新建小节'
)

// 方法
const handleCreateChapter = () => {
  currentAction.value = 'chapter'
  formData.value = { type: 'chapter' }
  dialogVisible.value = true
}

const handleCreateSection = (chapter) => {
  currentAction.value = 'section'
  formData.value = { type: 'section', parentId: chapter.id }
  dialogVisible.value = true
}

const handleNodeDblclick = (data) => {
  if(data.type === 'section') return
  handleRenameNode(data)
}

const openResourceDialog = () => {
  if (!selectedSection.value) {
    ElMessage.warning('请先选择小节');
    return;
  }
  
  switch (activeType.value) {
    case 'video':
      currentResourcePage.value = components.T_VideosPage;
      break;
    case 'document':
    case 'ppt':
      currentResourcePage.value = components.T_WordPage;
      break;
    case 'image':
      currentResourcePage.value = components.T_ExamBankPage;
      break;
  }
  
  visibleResourceDialog.value = true;
};

// 添加资源选择事件处理
const handleVideoSelected = (video) => {
  selectedResource.value = video;
   console.log('Video selected ID:', video.id); // 添加日志输出
};
const handleDocumentSelected = (doc) => {
  selectedResource.value = doc;
   console.log('Document selected ID:', doc.id); // 添加日志输出
};
const handleImageSelected = (image) => {
  selectedResource.value = image;
  console.log('Image selected ID:', image.id); // 添加日志输出
};

// 添加确认处理方法
const handleConfirmResource = async () => {
  if (!selectedResource.value) {
    ElMessage.warning('请先选择资源');
    return;
  }
  try {
      const res = await addResourceToSection({
        unit_id: selectedSection.value.id,
        resource_id: selectedResource.value.id
      });
      
      if(res.data.status === 1) {
        visibleResourceDialog.value = false;
        selectedResource.value = null;
        // 刷新资源列表
        handleNodeClick(selectedSection.value);
        ElMessage.success('添加资源成功');
      }
    } catch (error) {
      ElMessage.error('添加资源失败');
    }
  };


// const handleBeforeUpload = () => {}

// 修改重命名方法
const handleRenameNode = (node) => {
  renameFormData.value = {
    node: node,
    newName: node.label
  }
  renameDialogVisible.value = true
}

const handleConfirmRename = async () => {
  try {
    const { node, newName } = renameFormData.value
    if (!newName.trim()) {
      ElMessage.warning('名称不能为空')
      return
    }
    
    const res = await renameUnit({
      unit_id: node.id,
      unit_title: newName
    })
    
    if(res.data.status === 1) {
      ElMessage.success('重命名成功')
      node.label = newName
      // 如果是当前选中小节需要更新显示
      if(selectedSection.value?.id === node.id) {
        selectedSection.value.label = newName
      }
      renameDialogVisible.value = false
    }
  } catch (error) {
    console.error('重命名失败:', error)
    ElMessage.error('重命名失败，请稍后重试')
  }
}

const handleDelete = async (resource) => {
  try {
    await ElMessageBox.confirm(
      `确定删除资源 ${resource.name} 吗？`,
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const res = await deleteResources(resource.id);
    if(res.data.status === 1) {
      ElMessage.success('删除成功');
      const index = selectedSection.value.resources.findIndex(r => r.id === resource.id);
      if(index > -1) {
        selectedSection.value.resources.splice(index, 1);
      }
    }
  } catch (error) {
    // 用户取消操作自动捕获
  }
}

// 辅助方法
// const findNode = (nodes, id) => {
//   for(const node of nodes) {
//     if(node.id === id) return node
//     if(node.children) {
//       const found = findNode(node.children, id)
//       if(found) return found
//     }
//   }
//   return null
// }
</script>

<style scoped>
.cousename{
  font-weight: bold;
  color: rgb(36, 67, 130);
  font-size: 18px;
  margin-bottom: 8px;
}
.operation-bar {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
}

.create-button {
  font-size: 16px;
  background-color: #244382;
  color: #fff;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  height: 38px;
  transition: background-color 0.3s;
}

.create-button:hover {
  background-color: #376edc;
}

.upload-btn {
  margin-left: 10px;
}


.main-layout {
  display: flex;
  gap: 20px;
}

.left-tree {
  width: 400px;
  border-right: 1px solid #eee;
  padding-right: 20px;
}

.section-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 12px;
  color: rgb(55, 54, 54);
}

.node-actions {
  margin-left: auto;
  display: flex;
  gap: 4px;
}

.right-content {
  flex: 1;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.resource-types {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.resource-list {
  display: flex;
  flex-direction: column;
}
.resource-item:hover {
  background-color:#eef7ff;;
}

.resource-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0px;
}

.resource-info {
  display: flex;
  gap: 12px;
}

.upload-time {
  color: #888;
}

.resource-actions {
  display: flex;
  gap: 8px;
}

.video-cover {
  margin-left: 20px;
  display:flex;
  align-items: center;
  object-fit: cover;

}
.play-button {
  position: absolute;
  width: 50px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
}
.video-cover-container {
  position: relative;
  cursor: pointer; /* 更改鼠标为手型 */
}

.video-cover:hover .play-button {
  display: block; /* 鼠标悬停时显示播放按钮 */
}

.play-button img {
  width: 30px; /* 调整大小 */
  height: 30px;
  margin-right: 20px;
}
.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-name {
  margin-top: 8px;
  text-align: center;
}

.document-item,
.ppt-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.document-icon,
.ppt-icon {
  font-size: 24px;
}

.document-info,
.ppt-info {
  display: flex;
  flex-direction: column;
}

.upload-card {
  width: 100%;
}

.upload-card-inner {
  width: 100%;
  height: 160px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
}

.upload-text {
  margin-top: 8px;
  color: var(--el-color-primary);
}

.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
}
.empty-resource {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  gap: 20px;
}
.left-tree :deep(.el-tree-node__content) {
  min-height: 40px;  /* 将节点高度从默认的26px增加到40px */
  margin:  0;     /* 添加上下边距 */
}
.modal-overlay {
  z-index: 1000;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  width: 80vw;
  height: 80vh;
  background: white;
  border-radius: 10px;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  overflow-x: hidden;
}

.modal-actions {
    display: flex;
    justify-content: space-between;
    gap: 10px;
    padding-top: 10px;
    padding-bottom: 20px;
    margin-bottom: -8px;
    border-top: 1px solid #ddd;
    position: fixed;
    bottom: 63px;
    background: white;
}

.resource-types {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.resource-list {
  max-height: 400px;
  overflow-y: auto;
}
</style>
